package com.yifeng.repo.micro.service.server.engine.generate;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.sql.Types;
import java.util.Collections;

/**
 * Created by daibing on 2023/6/19.
 */
public class MybatisPlusGenerator {

    public static void mybatisPlusGenerateCode(MybatisPlusGeneratorConf conf) throws UnsupportedEncodingException {
        FastAutoGenerator.create(conf.getUrl(), conf.getUsername(), conf.getPassword())
                .globalConfig(builder -> builder.author(conf.getAuthor())
                                .outputDir(conf.getProjectAbsoluteDir() + "\\src\\main\\java").disableOpenDir()
                                .dateType(DateType.TIME_PACK)
                                /*.disableServiceInterface()*/)
                .dataSourceConfig(builder -> builder
                        .typeConvertHandler(((globalConfig, typeRegistry, metaInfo) -> {
                            if (metaInfo.getJdbcType().TYPE_CODE == Types.TINYINT && metaInfo.getLength() == 1) {
                                return DbColumnType.BOOLEAN;
                            } else {
                                return typeRegistry.getColumnType(metaInfo);
                            }
                        })))
                .packageConfig(builder -> builder.moduleName(conf.getModuleName())
                        .parent(conf.getParent())
                        .mapper("dao")
                        .pathInfo(Collections.singletonMap(OutputFile.xml, conf.getProjectAbsoluteDir() + "\\src\\main\\resources\\mybatis\\" + conf.getResourceName()))
                )
                .strategyConfig(builder -> builder
                        .addTablePrefix(conf.getTablePrefixList()).addInclude(conf.getIncludes())
                        .controllerBuilder().enableFileOverride().enableRestStyle()
                        .serviceBuilder().enableFileOverride().formatServiceFileName("%sService")
                        .entityBuilder().enableFileOverride().enableLombok().enableChainModel().enableRemoveIsPrefix()
                            .idType(IdType.ASSIGN_ID).disableSerialVersionUID().formatFileName("%sEntity")
                            .logicDeleteColumnName("is_deleted").logicDeletePropertyName("deleted")
                            .naming(NamingStrategy.underline_to_camel).columnNaming(NamingStrategy.underline_to_camel)
                        .mapperBuilder().enableFileOverride().enableBaseResultMap().enableBaseColumnList()/*.mapperAnnotation(Mapper.class)*/
                )
                .templateEngine(new MybatisPlusFreemarkerTemplateEngine())
                .execute();
    }

    public static void mybatisPlusGenerateCodeExample(String projectAbsoluteDir) {
        FastAutoGenerator.create("jdbc:mysql://192.168.254.37:59003/yfcloud_example", "yfcloud_example", "kPolU_2i354")
                .globalConfig(builder -> builder.author("daibing")
                                .outputDir(projectAbsoluteDir + "\\src\\main\\java").disableOpenDir()
                                .dateType(DateType.ONLY_DATE)
                                /*.disableServiceInterface()*/)
                .dataSourceConfig(builder -> builder
                        .typeConvertHandler(((globalConfig, typeRegistry, metaInfo) -> {
                            if (metaInfo.getJdbcType().TYPE_CODE == Types.TINYINT && metaInfo.getLength() == 1) {
                                return DbColumnType.BOOLEAN;
                            } else {
                                return typeRegistry.getColumnType(metaInfo);
                            }
                        })))
                .packageConfig(builder -> builder.moduleName("boss")
                        .parent("com.yifeng.base.sms.server")
                        .mapper("dao")
                        .pathInfo(Collections.singletonMap(OutputFile.xml, projectAbsoluteDir + "\\src\\main\\resources\\mybatis\\boss"))
                )
                .strategyConfig(builder -> builder
                        .addTablePrefix("sms_").addInclude("sms_user")
                        .controllerBuilder().enableFileOverride().enableRestStyle()
                        .serviceBuilder().enableFileOverride().formatServiceFileName("%sService")
                        .entityBuilder().enableFileOverride().enableLombok().enableChainModel().enableRemoveIsPrefix()
                            .idType(IdType.ASSIGN_ID).disableSerialVersionUID().formatFileName("%sEntity")
                            .logicDeleteColumnName("is_deleted").logicDeletePropertyName("deleted")
                            .naming(NamingStrategy.underline_to_camel).columnNaming(NamingStrategy.underline_to_camel)
                        .mapperBuilder().enableFileOverride().enableBaseResultMap().enableBaseColumnList()/*.mapperAnnotation(Mapper.class)*/
                )
                .templateEngine(new MybatisPlusFreemarkerTemplateEngine())
                .execute();
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        // 项目绝对路径，如果不填写则为当前项目地址 classpath
        File file = new File(MybatisPlusGenerator.class.getProtectionDomain().getCodeSource().getLocation().getFile());
        String projectAbsoluteDir = URLDecoder.decode(file.getParent(), StandardCharsets.UTF_8.name()).replace("\\target", "");
        mybatisPlusGenerateCodeExample(projectAbsoluteDir);
    }

}
